var RealWaveChart = function (params) {
    var self = this;
    self.chartId = params.chartId;
    self.chartQuery = params.chartQuery;
    self.option = null;
    self.chart = null;
    self.points = null;
    self.isInited = false;
    self.ajaxRequests = null;
    self.lineDataArray = new Array();
    self.seriesArray = new Array();
    self.render = function () {
        self.option.series = self.seriesArray;
        self.chart.setOption(self.option);
    };
    self.begin = function () {
        try {
            if (self.ajaxRequests) {
                $.each(self.ajaxRequests, function (i, d) {
                    if (d) {
                        d.abort();
                    }
                });
            }
        }
        catch (ex) {
            console.log(ex);
        }

        try {
            self.points = self.chartQuery.points;
            self.reset(self.points);

            self.ajaxRequests = new Array();
            $.each(self.points, function (i, d) {
                self.request(i, d);
            });
        }
        catch
            (e) {
            console.log(e.message);
        }
    };
    self.dataReceived = function (point, data) {
        var lineData = self.createLineData(point.deviceCode, point.pointCode, data.waveData);
        lineData.axis = {xMax: data.xMax, xMin: data.xMin, yMax: data.yMax, yMin: data.yMin};
        self.replaceLineData(point.deviceCode, point.pointCode, lineData);
        self.replaceSeriesData(point.deviceCode, point.pointCode, lineData.list);

        //获取最大最小值
        var ymax, ymin;
        $.each(self.lineDataArray, function (i, d) {
            if (ymax) {
                ymax = d.yMax;
            }
            if (ymin) {
                ymin = d.yMin;
            }

            if (ymax < d.yMax) {
                ymax = d.yMax;
            }

            if (ymin > d.yMin) {
                ymin = d.yMin;
            }
        });

        self.setAxis(ymax, ymin);
        self.render();
    };
    self.request = function (i, d) {
        var ap = ajaxPost(contextRoot + "realtime/getWave",
            d,
            function (data) {
                try {
                    self.dataReceived(d, data);
                }
                catch (e) {
                    console.log(e);
                }
                self.request(i, d);
            },
            function (error, xhr, status) {
                if (status != "abort") {
                    self.request(i, d);
                }
            }, 60000, false
        );
        self.ajaxRequests[i] = ap;
    };
    self.init = function () {
        self.chart = echarts.init(document.getElementById(self.chartId));
        self.option = {
            title: {
                left: 'left',
                text: '波形图'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    params = params[0];
                    var date = new Date(params.name);
                    return '时间:' + date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + ',值: ' + params.value[1];
                },
                axisPointer: {
                    animation: false
                }
            },
            legend: {
                tooltip: {
                    show: true
                },
                data: []
            },
            xAxis: {
                type: 'time',
                min: 'dataMin',
                max: 'dataMax',
                splitLine: {
                    lineStyle: {
                        color: ['#aaa', '#ddd']
                    }
                }
            },
            yAxis: {
                type: 'value',
                splitLine: {
                    lineStyle: {
                        color: ['#aaa', '#ddd']
                    }
                },
                axisLine: {
                    show: true
                }
            },
            series: []
        };
        self.render();
    };
    self.makesureInit = function () {
        if (self.isInited != true) {
            self.init();
            self.isInited = true;
        }
    };
    self.reset = function (points) {
        self.points = points;
        self.option.legend.data = new Array();
        self.lineDataArray = new Array();
        self.seriesArray = new Array();
        $.each(points, function (i, d) {
            var lineData = self.createLineData(d.deviceCode, d.pointCode);
            self.lineDataArray.push(lineData);
            var series = self.createSeries(d.pointName, d.deviceCode, d.pointCode, lineData, d.color);
            self.seriesArray.push(series);
            self.option.legend.data.push(d.pointCode);
        });
    };
    self.getLineData = function (deviceCode, pointCode) {
        var lineData = null;
        $.each(self.lineDataArray, function (i, d) {
            if (d.deviceCode == deviceCode && d.pointCode == pointCode) {
                lineData = d;
                return true;
            }
        });

        return lineData;
    };
    self.replaceLineData = function (deviceCode, pointCode, data) {
        $.each(self.lineDataArray, function (i, d) {
            if (d.deviceCode == deviceCode && d.pointCode == pointCode) {
                self.lineDataArray.splice(i, 1, data);
                return true;
            }
        });
    };
    self.createLineData = function (deviceCode, pointCode, defaultData) {
        var lineData = new Object();
        lineData.list = new Array();
        if (defaultData) {
            lineData.list = defaultData;
        }
        lineData.deviceCode = deviceCode;
        lineData.pointCode = pointCode;
        return lineData;
    };
    self.getSeries = function (deviceCode, pointCode) {
        var series = null;
        $.each(self.seriesArray, function (i, d) {
            if (d.deviceCode == deviceCode && d.pointCode == pointCode) {
                series = d;
                return true;
            }
        });
        return series;
    };
    self.replaceSeriesData = function (deviceCode, pointCode, data) {
        var series = self.getSeries(deviceCode, pointCode);
        if (series) {
            series.data = data;
        }
    }
    self.createSeries = function (name, deviceCode, pointCode, data, color) {
        var series = {
            name: name,
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: data.list,
            itemStyle: {
                normal: {
                    color: color,
                    borderColor: '#fff',
                    borderWith: 1,
                    shadowBlur: 2,
                    shadowOffsetX: 2,
                    shadowOffsetY: 5
                }
            },
            lineStyle: {
                normal: {
                    width: 1,
                    shadowColor: 'rgba(112, 155, 233, 0.5)',
                    shadowBlur: 4,
                    shadowOffsetY: 4
                }
            },
            markLine: {
                silent: true,
                symbol: false,
                animation: false,
                label: {
                    normal: {
                        show: false
                    }
                },
                data: [{
                    yAxis: -0.10
                }],
                lineStyle: {
                    normal: {
                        opacity: 0.5
                    }
                }
            }
        };
        series.deviceCode = deviceCode;
        series.pointCode = pointCode;
        return series;
    };
    self.addTreeNode = function (treeNode) {
        if (treeNode.nodeType == 4) {
            //动态测点
            ajaxPost(contextRoot + "dynamicPoint/getDetailDynamicPoint/" + treeNode.id, {}, function (data) {
                var itemHtmlFormat =
                    '<div class="item_point">' +
                    '<div class="label label-info item_point_name">{0}</div>' +
                    '<div class="item_point_main">' +
                    '<div class="item_point_args">' +
                    '<span class="badge badge-success item_point_arg">{2}</span><span class="badge badge-warning item_point_arg">关联测点编码:{3}</span>' +
                    '<span class="badge badge-important item_point_arg">采样频率:{4}</span><span class="badge item_point_arg">采样间隔:{5}</span>' +
                    '<span class="badge badge-info item_point_arg">分析点数:{6}</span><span class="badge badge-inverse item_point_arg">采样方式:{7}</span>' +
                    '</div>' +
                    '<div class="item_point_eigens">{1}</div>' +
                    '</div>' +
                    '<div class="item_point_actions"><a><i class="icon-remove"></i></a></div>' +
                    '<div class="clear"></div> ' +
                    '</div>' +
                    '<div>';
                var eigensHtml = '';
                $.each(data.eigenCheckedValues, function (i, d) {
                    eigensHtml += String.format('<div class="checkbox checkbox-primary checkbox-inline">' +
                        '                        <input type="checkbox" id="eigen_{2}_{0}" value="{0}">' +
                        '                        <label for="eigen_{2}_{0}">{1}</label>' +
                        '                    </div>', d.code, d.name, data.entity.id);
                })
                var itemHtml = String.format(itemHtmlFormat, data.entity.name, eigensHtml, data.pointTypeText,
                    data.entity.code, data.entity.frequency, data.entity.sampleInterval, data.entity.dataCount, data.entity.sampleType);
                $("#trend_query_container").append(itemHtml);
            });
        }
        else if (treeNode.nodeType == 5) {
            //动态测点
            ajaxPost(contextRoot + "staticPoint/getDetailStaticPoint/" + treeNode.id, {}, function (data) {
                var itemHtmlFormat =
                    '<div class="item_point">' +
                    '<div class="label label-info item_point_name">{0}</div>' +
                    '<div class="item_point_main">' +
                    '<div class="item_point_args">' +
                    '<span class="badge badge-success item_point_arg">{2}</span><span class="badge badge-warning item_point_arg">关联测点编码:{3}</span>' +
                    '<span class="badge badge-important item_point_arg">采样间隔:{4}</span>' +
                    '</div>' +
                    '<div class="item_point_eigens">{1}</div>' +
                    '</div>' +
                    '<div class="item_point_actions"><a><i class="icon-remove"></i></a></div>' +
                    '<div class="clear"></div> ' +
                    '</div>' +
                    '<div>';
                var eigensHtml = '';
                $.each(data.eigenCheckedValues, function (i, d) {
                    eigensHtml += String.format('<div class="checkbox checkbox-primary checkbox-inline">' +
                        '                        <input type="checkbox" id="eigen_{2}_{0}" value="{0}">' +
                        '                        <label for="eigen_{2}_{0}">{1}</label>' +
                        '                    </div>', d.code, d.name, data.entity.id);
                })
                var itemHtml = String.format(itemHtmlFormat, data.entity.name, eigensHtml, data.pointTypeText, data.entity.code, data.entity.sampleInterval);
                $("#trend_query_container").append(itemHtml);
            });
        }
    };
    self.setAxis = function (ymax, ymin) {
        self.option.yAxis.max = ymax;
        self.option.yAxis.min = ymin;
    };
    self.addTreeNode = function (treeNode) {
        self.chartQuery.addTreeNode(treeNode);
    };
}